﻿using Application;
using Entity;
using Entity.UserRoles;
using EntityFrameWorkCore;
using FrameWorkCore;
using FrameWorkCore.JWT;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Repository.Repository;
using System.Collections;
using Utility;
using WebApi6.Controllers.Auth.Dto;

namespace WebApi6.Controllers
{
    public class AuthController: ControllerBases
    {
    


        private IJWTAuthService JWTAuthService;

        public IHttpContextAccessor HttpContextAccessor { get; set; }

        public IHttpClientFactory HttpClientFactory { get; set; }

     

        public AuthController(IJWTAuthService _JWTAuthService) => (JWTAuthService) = (_JWTAuthService);


        [AllowAnonymous]
        [HttpPost]
        public async ValueTask<string> LoginIn([FromBody] UserDto dto)
        {
            try
            {
                Guid? subjectId = null;
                var lowUserName = dto.UserName.ToLower();
                var encPassWord = DESEncryptExtension.Encrypt(dto.PassWord);
                var user = await UserRep.FirstOrDefaultAsync(x => x.UserName.ToLower().Equals(lowUserName) && x.PassWord.Equals(encPassWord));
                if (user is null  )
                {
                   if (dto.UserName.ToLower() == "admin" && (await UserRep.FirstOrDefaultAsync(x => x.UserName.ToLower().Equals(lowUserName))) is null)
                   {
                        
                        subjectId = (await UserRep.InsertAsync(new User() { UserName = dto.UserName, PassWord = encPassWord, EmailAddress = "1486971629@qq.com" })).Id;
                        var role = await RoleRep.InsertAsync(new Role { RoleName = "admin", RoleDescribe = "系统管理员" });
                        await UserRoleRep.InsertAsync(new UserRole { UserId = subjectId.Value,RoleId = role.Id });
                    }                    
                   else
                        throw new Exception("The user name or password is not correct!");

                }
                else
                    subjectId = user.Id;

                    

                #region Ids4
                //var httpClient = HttpClientFactory.CreateClient();
                //var disco = await httpClient.GetDiscoveryDocumentAsync("http://localhost:5001");
                //var tokenResponse = await httpClient.RequestPasswordTokenAsync(new PasswordTokenRequest
                //{
                //    Address = disco.TokenEndpoint,
                //    ClientId = "IdentityAuth",
                //    ClientSecret = "Secret",
                //    UserName = UserDto.account,
                //    Password = UserDto.password,
                //    Scope = "All",
                //});
                //var token = tokenResponse.AccessToken;

                ////var httpClient1 = HttpClientFactory.CreateClient();
                ////httpClient1.SetBearerToken(token);

                ////var ApiResource = await httpClient1.GetAsync(disco.UserInfoEndpoint);
                ////var content = await ApiResource.Content.ReadAsStringAsync();
                //return token;
                #endregion

                return JWTAuthService.GetAuthToken(subjectId.Value.ToString());
            }
            catch (Exception e)
            {

                throw new UserFriendlyException(e.Message);
            }
                
        }

        [HttpPost]
        public async ValueTask Logout()
            => await HttpContext.SignOutAsync(JwtBearerDefaults.AuthenticationScheme);

        
    }
}
